package keystore;

import java.io.FileInputStream;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.SSLServerSocketFactory;
import javax.net.ssl.SSLSocket;


public class KeyStoreServer {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		char[] password = "1q2w3e4r".toCharArray();
		try {
			KeyStore ks = KeyStore.getInstance("JKS");
			FileInputStream fis = null;

			try {
				fis = new FileInputStream("hieDataStore.crt");
				ks.load(fis, password);
			} catch (CertificateException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {
				if(fis != null) try { fis.close(); } catch(Exception e) {}
			}

			KeyManagerFactory kmf = null;
			if(System.getProperty("java.vm.vendor").toUpperCase().indexOf("IBM") != -1) {
				// IBM JVM Algorithm
				kmf = KeyManagerFactory.getInstance("ibmX509");
			} else {
				// SUN JVM Algorithm
				kmf = KeyManagerFactory.getInstance("SunX509");
			}

			kmf.init(ks, password);

			SSLContext ctx = SSLContext.getInstance("SSL");
			ctx.init(kmf.getKeyManagers(), null, null);
			SSLServerSocketFactory sslssf = (SSLServerSocketFactory)ctx.getServerSocketFactory();
		
			SSLServerSocket sslServerSocket = (SSLServerSocket)sslssf.createServerSocket(Integer.parseInt(args[0]));     
			sslServerSocket.setEnabledCipherSuites(sslssf.getDefaultCipherSuites());

			while (true) {
				SSLSocket clientSocket = (SSLSocket) sslServerSocket.accept();
				Thread thread = new Worker(new SSLConnection(clientSocket)); 
				thread.start();
				thread.join();
			}
		} catch (Exception e) {
			;
		}		

	}

}
